<?php
class ProductController extends \BaseController {

	protected $layout = 'layout/default';
	
	/**
	 * Shows an individual product by its ID
	 */
	public function showProductByid($id)
	{		
		$product = Product::find($id);
		$categories = Category::all();
		$seo 		= $product->seo()->first();
		// Get all reviews that are not spam for the product and paginate them
		$reviews = 	$product->reviews()
							->with('user') // Eager Loading
							->approved()
							->notSpam()
							->orderBy('created_at','desc')
							->paginate(2);
		
		$this->layout->content = View::make('product.single', array(
			'product'	=> $product,
			'reviews'	=> $reviews,
			'categories'=> $categories,
			'seo'		=> $seo
		));
	}
	
	public function postReview($id)
	{
		$input = [
			'comment' => Input::get('comment'),
			'rating'  => Input::get('rating')
		];
		$review = new Review;
		
		$validator = Validator::make( $input, $review->getCreateRules());
		
		if ($validator->passes()) {
			$review->storeReviewForProduct($id, $input['comment'], $input['rating']);
			return Redirect::to('product/' . $id . '#reviews-anchor')->with('review_posted', true);
		}
		
		return Redirect::to('product/' . $id . '#reviews-anchor')->withErrors($validator)->withInput();
	}
}